package org.jeecg.modules.Inventory.controller;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.Inventory.entity.Inventory;
import org.jeecg.modules.Inventory.entity.ReportInventoryVO;
import org.jeecg.modules.Inventory.service.IInventoryService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.basicSku.entity.BasicSku;
import org.jeecg.modules.basicSku.service.IBasicSkuService;
import org.jeecg.modules.checkInventory.entity.CheckInventory;
import org.jeecg.modules.checkInventory.service.ICheckInventoryService;
import org.jeecg.modules.dataLog.entity.DataLog;
import org.jeecg.modules.dataLog.service.IDataLogService;
import org.jeecg.modules.inOrder.entity.InOrderZi;
import org.jeecg.modules.inventoryPt.entity.InventoryPt;
import org.jeecg.modules.operationLog.entity.OperationLog;
import org.jeecg.modules.operationLog.service.IOperationLogService;
import org.jeecg.modules.outOrder.entity.OutOrder;
import org.jeecg.modules.outOrder.entity.OutOrderZi;
import org.jeecg.modules.outOrder.service.IOutOrderService;
import org.jeecg.modules.outOrder.service.IOutOrderZiService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 库存表
 * @Author: jeecg-boot
 * @Date:   2024-06-26
 * @Version: V1.0
 */
@Api(tags="库存表")
@RestController
@RequestMapping("/Inventory/inventory")
@Slf4j
public class InventoryController extends JeecgController<Inventory, IInventoryService> {
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private ICheckInventoryService checkInventoryService;
	@Autowired
	private IOutOrderService outOrderService;
	@Autowired
	private IOutOrderZiService outOrderZiService;
	@Autowired
	private IDataLogService dataLogService;
	@Autowired
	private IOperationLogService operationLogService;
	@Autowired
	private IBasicSkuService basicSkuService;

	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;
	
	/**
	 * 分页列表查询
	 *
	 * @param inventory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "库存表-分页列表查询")
	@ApiOperation(value="库存表-分页列表查询", notes="库存表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Inventory inventory,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String location = inventory.getLocation();
		inventory.setLocation(null);
		QueryWrapper<Inventory> queryWrapper = QueryGenerator.initQueryWrapper(inventory, req.getParameterMap());
		if (location != null && !location.isEmpty()) {
			queryWrapper.like("location", location);
		}
		queryWrapper.eq("status", 0);
		Page<Inventory> page = new Page<Inventory>(pageNo, pageSize);
		IPage<Inventory> pageList = inventoryService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/skuList")
	 public Result<?> skuList(Inventory inventory,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<Inventory> queryWrapper = QueryGenerator.initQueryWrapper(inventory, req.getParameterMap());
		 queryWrapper.select("sku_code","SUM(number) AS number");
		 queryWrapper.groupBy("sku_code");
		 queryWrapper.eq("status", 0);
		 Page<Inventory> page = new Page<Inventory>(pageNo, pageSize);
		 IPage<Inventory> pageList = inventoryService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @GetMapping(value = "/locationList")
	 public Result<?> locationList(Inventory inventory,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								 HttpServletRequest req) {
		 String location = inventory.getLocation();
		 inventory.setLocation(null);
		 QueryWrapper<Inventory> queryWrapper = QueryGenerator.initQueryWrapper(inventory, req.getParameterMap());
		 queryWrapper.select("sku_code","SUM(number) AS number","location");
		 if (location != null && !location.isEmpty()) {
			 queryWrapper.like("location", location);
		 }
		 queryWrapper.eq("status", 0);
		 queryWrapper.groupBy("sku_code", "location");
		 Page<Inventory> page = new Page<Inventory>(pageNo, pageSize);
		 IPage<Inventory> pageList = inventoryService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @PostMapping(value = "/createCheck")
	 public Result<?> createCheck(@RequestBody List<Inventory> inventories) {
		 List<CheckInventory> list = new ArrayList<>();
		 for (Inventory inventory : inventories) {
			 CheckInventory checkInventory = new CheckInventory();
			 checkInventory.setSkuCode(inventory.getSkuCode()).setNumber(inventory.getNumber())
					 .setLocation(inventory.getLocation()).setStatus(1).setInventoryId(inventory.getId());
			 list.add(checkInventory);
		 }
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 OperationLog operationLog = new OperationLog();
		 operationLog.setOperationTime(new Date()).setOperationType("生成盘点单").setOperator(user.getRealname());
		 checkInventoryService.saveBatch(list);
		 operationLogService.save(operationLog);
		 return Result.OK("生成成功!", null);
	 }

	 @PostMapping(value = "/createOutOrder")
	 public Result<?> createOutOrder(@RequestParam(name="ids",required=true) String ids) {
		 List<Inventory> inventories = inventoryService.listByIds(Arrays.asList(ids.split(",")));
		 OutOrder outOrder = new OutOrder();
		 outOrder.setOutTime(new Date());
		 List<OutOrderZi> list = new ArrayList<>();
		 for (Inventory inventory : inventories) {
			 OutOrderZi outOrderZi = new OutOrderZi();
			 outOrderZi.setSkuCode(inventory.getSkuCode()).setNumber(inventory.getNumber())
					 .setSkuName(inventory.getSkuName()).setLocation(inventory.getLocation())
					 .setInventoryId(inventory.getId()).setInTime(inventory.getInTime())
					 .setInventory(inventory.getNumber());
			 list.add(outOrderZi);
		 }
		 outOrderService.saveMain(outOrder, list);
		 return Result.OK("生成成功!", null);
	 }

	/**
	 *   添加
	 *
	 * @param inventory
	 * @return
	 */
	@AutoLog(value = "库存表-添加")
	@ApiOperation(value="库存表-添加", notes="库存表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody Inventory inventory) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		DataLog dataLog = new DataLog();
		dataLog.setOperator(user.getRealname()).setOperationTime(new Date())
				.setOperationType("新增").setOperationClass("库存表")
				.setUpdated(inventory.toString());
		inventoryService.save(inventory);
		dataLogService.save(dataLog);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param inventory
	 * @return
	 */
	@AutoLog(value = "库存表-编辑")
	@ApiOperation(value="库存表-编辑", notes="库存表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody Inventory inventory) {
		Inventory byId = inventoryService.getById(inventory.getId());
		if (byId == null) {
			return Result.error("未找到对应数据");
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		DataLog dataLog = new DataLog();
		dataLog.setOperator(user.getRealname()).setOperationTime(new Date())
				.setOperationType("编辑").setOperationClass("库存表")
				.setOriginal(byId.toString()).setUpdated(inventory.toString());
		inventoryService.updateById(inventory);
		dataLogService.save(dataLog);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "库存表-通过id删除")
	@ApiOperation(value="库存表-通过id删除", notes="库存表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		Inventory byId = inventoryService.getById(id);
		if (byId == null) {
			return Result.error("未找到对应数据");
		}
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		DataLog dataLog = new DataLog();
		dataLog.setOperator(user.getRealname()).setOperationTime(new Date())
				.setOperationType("删除").setOperationClass("库存表")
				.setOriginal(byId.toString());
		inventoryService.removeById(id);
		dataLogService.save(dataLog);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "库存表-批量删除")
	@ApiOperation(value="库存表-批量删除", notes="库存表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		List<Inventory> inventories = inventoryService.listByIds(list);
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Date date = new Date();
		List<DataLog> dataLogs = new ArrayList<>();
		for (Inventory inventory : inventories) {
			DataLog dataLog = new DataLog();
			dataLog.setOperator(user.getRealname()).setOperationTime(date)
					.setOperationType("删除").setOperationClass("库存表")
					.setOriginal(inventory.toString());
			dataLogs.add(dataLog);
		}
		this.inventoryService.removeByIds(list);
		dataLogService.saveBatch(dataLogs);
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "库存表-通过id查询")
	@ApiOperation(value="库存表-通过id查询", notes="库存表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Inventory inventory = inventoryService.getById(id);
		if(inventory==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(inventory);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param inventory
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Inventory inventory) {
        return super.exportXlsStatus(request, inventory, Inventory.class, "库存表");
    }

	 @RequestMapping(value = "/skuExportXls")
	 public ModelAndView skuExportXls(HttpServletRequest request, Inventory inventory) {
		 // Step.1 组装查询条件
		 QueryWrapper<Inventory> queryWrapper = QueryGenerator.initQueryWrapper(inventory, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.select("sku_code","SUM(number) AS number");
		 queryWrapper.eq("status", 0);
		 queryWrapper.groupBy("sku_code");
		 // Step.2 获取导出数据
		 List<Inventory> pageList = inventoryService.list(queryWrapper);
		 List<Inventory> exportList = null;
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }
		 List<ReportInventoryVO> reportInventoryVOList = exportList.stream()
				 .map(ReportInventoryVO::new)
				 .collect(Collectors.toList());
		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "库存表"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, ReportInventoryVO.class);
		 //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		 ExportParams  exportParams=new ExportParams("库存表" + "报表", "导出人:" + sysUser.getRealname(), "库存表");
		 exportParams.setImageBasePath(upLoadPath);
		 //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		 mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, reportInventoryVOList);
		 return mv;
	 }

	 @RequestMapping(value = "/locationExportXls")
	 public ModelAndView locationExportXls(HttpServletRequest request, Inventory inventory) {
		 // Step.1 组装查询条件
		 QueryWrapper<Inventory> queryWrapper = QueryGenerator.initQueryWrapper(inventory, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.select("sku_code","SUM(number) AS number","location");
		 queryWrapper.eq("status", 0);
		 queryWrapper.groupBy("sku_code", "location");
		 // Step.2 获取导出数据
		 List<Inventory> pageList = inventoryService.list(queryWrapper);
		 List<Inventory> exportList = null;
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }
		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "库存表"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, Inventory.class);
		 //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		 ExportParams  exportParams=new ExportParams("库存表" + "报表", "导出人:" + sysUser.getRealname(), "库存表");
		 exportParams.setImageBasePath(upLoadPath);
		 //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		 mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Inventory.class);
    }

	 private String getId(Inventory item) {
		 try {
			 return PropertyUtils.getProperty(item, "id").toString();
		 } catch (Exception e) {
			 e.printStackTrace();
			 return null;
		 }
	 }

	 @AutoLog(value = "库存表-测试")
	 @ApiOperation(value="库存表-测试", notes="库存表-测试")
	 @GetMapping(value = "/test")
	 public Result<?> test() {
		 List<Inventory> inventories = inventoryService.list();
		 List<BasicSku> list = basicSkuService.list();
		 Map<String, BasicSku> map = list.stream()
				 .collect(Collectors.toMap(BasicSku::getSkuCode, Function.identity()));
		 for (Inventory inventory : inventories) {
			 String skuCode = inventory.getSkuCode();
			 if (map.containsKey(skuCode)) {
				 BasicSku sku = map.get(skuCode);
				 inventory.setSkuName(sku.getSkuName());
				 inventory.setBrand(sku.getBrand());
			 }
		 }
		 inventoryService.updateBatchById(inventories);
		 return Result.OK();
	 }

	 @GetMapping("/m/getBySku")
	 public Result<?> getBySku(@RequestParam(name = "skuCode") String skuCode) {
		 LambdaQueryWrapper<Inventory> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(Inventory::getSkuCode, skuCode);
		 List<Inventory> list = inventoryService.list(wrapper);
		 if (list.isEmpty()){
			 return Result.error("未找到市贩品【"+skuCode+"】品番的库存");
		 }
		 return Result.OK(list);
	 }

}
